import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/common/common_services.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/func_utils.dart';

import '../../../model/picture_upload_setting.dart';
import 'dart:convert' as convert;

class SiteSettingController extends GetxController {
  late int siteId;
  var siteName = '';
  var imageString = '';
  var energyOptions = '1';
  //站点当前货币
  String monetaryUnitName = '';
  List<Widget> settingItemsList = [];

  /// 站点服务
  SiteServices siteServices = Get.put(SiteServices());
  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      Log.d('Get.arguments=====' + Get.arguments.toString());
      siteId = Get.arguments['id'];
      siteName = Get.arguments['siteName'].toString();
      if (Get.arguments['energyOptions'] != null) {
        energyOptions = Get.arguments['energyOptions'];
      }
      if (Get.arguments['monetaryUnitName'] != null) {
        monetaryUnitName = Get.arguments['monetaryUnitName'];
      }
    }
    Log.d('energyOptions=====' + energyOptions.toString());
    if (FuncUtils.isPassAuthority(
        [PermissionConstant.homeSiteManageSettingDevice])) {
      settingItemsList.add(
        _getSetItem(
          ImageAssets.siteSettingAccessDevice,
          ResKey.deviceManage.tr,
          toSiteDeviceList,
        ),
      );
    }
    if (FuncUtils.isPassAuthority(
        [PermissionConstant.homeSiteManageSettingBaseInfo])) {
      settingItemsList.add(
        _getSetItem(ImageAssets.siteSettingBasicInfo, ResKey.basicInfo.tr, () {
          Get.toNamed(RouterPath.siteSiteSettingBaseInfo,
              arguments: {'siteId': siteId});
        }),
      );
    }
      if (FuncUtils.isPassAuthority(
          [PermissionConstant.homeSiteManageSettingElectric])) {
        settingItemsList.add(
          _getSetItem(
              ImageAssets.siteSettingElecPrice,
              ResKey.siteOverviewElectricitySetting.tr,
              goSietElecPriceSettingView),
        );
      }
      if (FuncUtils.isPassAuthority(
          [PermissionConstant.homeSiteManageSettingMonitor])) {
        settingItemsList.add(_getSetItem(
            ImageAssets.siteSettingCheck, ResKey.siteOverviewRunObserver.tr,
            () {
          Get.toNamed(RouterPath.siteObserverList,
              arguments: {'siteId': siteId});
        }));
      }
      if (FuncUtils.isPassAuthority( [PermissionConstant.homeSiteManageSettingParams])) {
        settingItemsList.add(
          _getSetItem(
            ImageAssets.siteSettingParamSet,
            ResKey.parameterSets.tr,
            () {
              Get.toNamed(RouterPath.siteSettingParamSetPage,
                  arguments: {'siteId': siteId});
            },
          ),
        );
      }

      if (FuncUtils.isPassAuthority(
          [PermissionConstant.homeSiteManageSettingVideo])) {
        settingItemsList.add(
          _getSetItem(
            ImageAssets.siteVideoMonitor,
            ResKey.videoMonitorSetting.tr,
            () {
              Get.toNamed(RouterPath.videoMonitorSettingPage,
                  arguments: {'siteId': siteId});
            },
          ),
        );
      }
    getSiteDetail(siteId);
  }

  getSiteDetail(int siteId) async {
    showLoading(toast: ResKey.loading.tr);
    var result =
        await siteServices.getSiteDetail({'siteId': siteId}, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null && result['overviewPicture'] != null) {
      List list = jsonDecode(result['overviewPicture']);
      if (list.isNotEmpty) {
        imageString = list.first;
      }
    }
    update();
  }

  goSietElecPriceSettingView() {
    Get.toNamed(RouterPath.siteElecPriceSetting, arguments: {
      'siteId': siteId,
      'energyOptions': energyOptions,
      'monetaryUnitName': monetaryUnitName
    });
  }

  toSiteDeviceList() {
    Get.toNamed(RouterPath.siteDeviceList, arguments: {'siteId': siteId});
  }

  Future<ImageSource?> askUserForImageSource(BuildContext context) async {
    return await showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        cancelButton: CupertinoActionSheetAction(
          isDestructiveAction: true,
          child: Text(
            ResKey.cancel.tr,
            style: const TextStyle(color: Colour.primaryColor),
          ),
          onPressed: () {
            Navigator.pop(context, null);
          },
        ),
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: Text(
              ResKey.camera.tr,
              style: const TextStyle(color: Colour.warningTextColor),
            ),
            onPressed: () async {
              _handleImage(context, ImageSource.camera);
            },
          ),
          CupertinoActionSheetAction(
            child: Text(ResKey.gallery.tr),
            onPressed: () {
              _handleImage(context, ImageSource.gallery);
            },
          ),
        ],
      ),
    );
  }

  _handleImage(BuildContext context, ImageSource source) async {
    Navigator.pop(context, source);
    final ImagePicker imagePicker = ImagePicker();
    final image = await imagePicker.pickImage(source: source, imageQuality: 50);
    if (image == null) {
      return;
    }
    var cropSettings = const ImageManipulationSettings(
        enableCropping: true, compressQuality: 50);
    // crop image if requested
    CroppedFile? finalImage = CroppedFile(image.path);
    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: image.path,
      // aspectRatio: cropSettings.aspectRatio,
      maxWidth: cropSettings.maxWidth,
      maxHeight: cropSettings.maxHeight,
      uiSettings: [
        IOSUiSettings(
            doneButtonTitle: ResKey.confirm.tr,
            cancelButtonTitle: ResKey.cancel.tr),
        AndroidUiSettings(
            toolbarTitle: '', hideBottomControls: true), //没办法 ，只能干掉工具栏支持国际化版本
      ],
    );
    var file = File(croppedFile!.path);
    uploadImage(file);
  }

  ///上传单张图片
  void uploadImage(File? image) async {
    if (image != null) {
      showLoading(toast: ResKey.loading.tr);
      var result = await CommonServices().upload(image);
      dismissLoading();
      Log.d('result===' + result.toString());
      if (result != null && result['url'] != null) {
        setSiteCover(result['url'].toString());
      }
    }
  }

  ///设置站点概览图

  void setSiteCover(String imageUrl) async {
    showLoading(toast: ResKey.loading.tr);
    var param = {
      'siteId': siteId,
      'overviewPicture': jsonEncode([imageUrl]),
    };
    Log.d('param===' + param.toString());
    var result = await siteServices.editSiteInfo(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      imageString = imageUrl;
      update();
    }
  }

  _getSetItem(String image, String title, Function() callback) {
    return GestureDetector(
        onTap: () {
          Log.d('image==$callback');
          callback();
        },
        child: Container(
          width: 160.w,
          height: 118,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.w), // 设置圆角
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.08), // 设置阴影颜色
                blurRadius: 24, // 阴影模糊程度
                offset: const Offset(0, 4), // 阴影偏移量
              ),
            ],
          ),
          child: Column(
            children: [
              const SizedBox(
                height: 20,
              ),
              Image(
                image: AssetImage(image),
                height: 48.w,
                width: 48.w,
              ),
              const SizedBox(
                height: 14,
              ),
              SizedBox(
                width: 160.w, // CircleContainer宽度
                child: Center(
                  child: Text(
                    title,
                    overflow: TextOverflow.ellipsis,
                    softWrap: true,
                    style: TextStyles.styleWith(
                      14.sp,
                      color: Colour.mainTextColor,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}
